from Functions import *

class Fortune(db.Model):
    hash = db.StringProperty()
    content = db.TextProperty()
    date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<html><head><title>Thinkgeek Fotune Files</title></head><body>')
		# Write the submission form
        self.response.out.write("""
              <form action="/sign" method="post">
                <div><input type="text" name="content"></textarea></div>
                <div><input type="submit" value="Sign Guestbook"></div>
              </form>
			  """)

        fortunes = db.GqlQuery("SELECT * FROM Fortune ORDER BY hash ASC")
	j = 0
        for fortune in fortunes:
			self.response.out.write('Hash of <b>%s</b>:' %cgi.escape(fortune.hash))
			self.response.out.write('<blockquote>%s</blockquote>' %cgi.escape(fortune.content))
			j += 1
	self.response.out.write('There are currently '+str(j)+' entries.')

        # Write the footer of the page
        self.response.out.write("""
            </body>
          </html>""")

class Guestbook(webapp.RequestHandler):
    def post(self):
    
	try: number = int(self.request.get('content'))
	except: 
		print("Error in int'ing the value")
		number = 1
	j = 0
	while j<number:
		fortune = Fortune()
		a = urllib.urlopen(test).read()
		b = regexhtml(htmlparser(a))
		newhash = md5(b)
		if db.GqlQuery("SELECT * FROM Fortune WHERE hash = :1", str(newhash)) == []:
			try:
				fortune.content = b
				fortune.hash = hash
				fortune.put()
			except: pass
		else: logging.debug("The hash "+newhash+" is already in the db.")
		j = j+1
	self.redirect('/')

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/sign', Guestbook)],
                                     debug=True)

def main():
    run_wsgi_app(application)


if __name__ == "__main__":
    main()